package com.xy.biz.mc.service.impl;

import com.xy.biz.mc.service.ServerEndPointService;
import com.xy.lang.domain.Ipv4;
import com.xy.lang.util.NetUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class ServerEndPointServiceImpl implements ServerEndPointService, InitializingBean {

    @Value("${server.port}")
    private int port;

    private long serverId;

    @Override
    public void afterPropertiesSet() throws Exception {
        toServerId(NetUtils.getHostAddress(), port);
    }

    @Override
    public Long getServerId() {
        return serverId;
    }

    @Override
    public String getIp() {
        return Ipv4.parse((int)serverId).toString();
    }

    private void toServerId(String ip, int port) {
        long part1 = (long)port << 47;
        int part2 = new Ipv4(ip).getValue();
        serverId = part1 | (long)part2;
    }


    /// tests

    public static void main(String[] args) throws Exception {
        ServerEndPointServiceImpl serverEndPointService = new ServerEndPointServiceImpl();

        serverEndPointService.afterPropertiesSet();
        System.out.println(serverEndPointService.getServerId());
        System.out.println(serverEndPointService.getIp());

        serverEndPointService.toServerId("127.0.0.1", 80);
        System.out.println(serverEndPointService.getServerId());
        System.out.println(serverEndPointService.getIp());

        serverEndPointService.toServerId("47.104.153.211", 65535);
        System.out.println(serverEndPointService.getServerId());
        System.out.println(serverEndPointService.getIp());
    }

}
